package com.freeter.JsonUtil;

import java.io.IOException;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.freeter.model.User;
import com.freeter.test.TimeTest;

public class JacksonUtil {
	private static ObjectMapper mapper = new ObjectMapper();

	public static String bean2Json(Object obj) throws IOException {
		StringWriter sw = new StringWriter();
		JsonGenerator gen = new JsonFactory().createGenerator(sw);
		mapper.writeValue(gen, obj);
		//mapper.writeValueAsString(obj); 
		gen.close();
		return sw.toString();
	}

	public static <T> T json2Bean(String jsonStr, Class<T> objClass)
			throws JsonParseException, JsonMappingException, IOException {
		return mapper.readValue(jsonStr, objClass);
	}

	public static List json2Bean(String jsonStr, Class<?> collectionClass, Class<?>... elementClasses)
			throws Exception {
		JavaType javaType = mapper.getTypeFactory().constructParametricType(collectionClass, elementClasses);
		List list = (List) mapper.readValue(jsonStr, javaType);
		return list;
	}

 
	public static void main(String agrs[]) throws Exception {
		String jsonText = Txt2String.txt2String("data2.txt");
		Long nowTime = TimeTest.nowTime();
		List<HashMap> list = new ArrayList<HashMap>();
		List list2 = (List) json2Bean(jsonText, list.getClass(),User.class);
		TimeTest.endTime(nowTime);

	}
}
